package cn.edu.zhku.swagger.config;


import cn.edu.zhku.swagger.response.ResponseEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class SwaggerConfig {

    @Value("${swagger.enabled}")
    private Boolean swaggerEnabled;

    @Bean
    public Docket getDocket() {
        List responseMessageList = new ArrayList();
        Arrays.stream(ResponseEnum.values()).forEach(responseEnum -> {
            responseMessageList.add(
                    new ResponseMessageBuilder().code(responseEnum.getCode()).message(responseEnum.getMsg())
                    .build());
        });
        return new Docket(DocumentationType.SWAGGER_2)
                .globalResponseMessage(RequestMethod.GET, responseMessageList)
                .globalResponseMessage(RequestMethod.POST, responseMessageList)
                .globalResponseMessage(RequestMethod.PUT, responseMessageList)
                .globalResponseMessage(RequestMethod.PATCH, responseMessageList)
                .globalResponseMessage(RequestMethod.DELETE, responseMessageList)
                .apiInfo(apiInfo())
                .enable(swaggerEnabled)  // 是否开启swagger
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.edu.zhku.controller"))  // 扫描的包路径
                .paths(PathSelectors.any())  // 不做url过滤
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList<>();
        apiKeyList.add(new ApiKey("token", "token", "header"));
        return apiKeyList;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("^(?!auth).*$"))
                .build());
        return securityContexts;
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("token", authorizationScopes));
        return securityReferences;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .contact(new Contact("LianWu", "", "lianwu930@126.com"))
                // 文档标题
                .title("peanut项目接口文档")
                // 文档描述
                .description("主要涉及操作用户，群组，任务，表单的相关API说明\n" +
                        "1.注意接口请求的类型\n" +
                        "2.返回的数据中若有null，则不显示，若集合为空，则显示[]\n" +
                        "3.当返回列表数据时，如群组列表，任务列表等，可传参pageNum表示第几页，pageSize表示每页记录数，否则将采用默认分页\n" +
                        "如果pageSize=0就会查询出全部的结果（相当于没有执行分页查询）\n" +
                        "4.当请求中有userId参数时，若不提供userId或者userId为-1，则将取当前登录用户的userId\n" +
                        "5.所有的更新请求前最好先筛选需要更新的部分，不要将整个表单的数据全部提交，即只更新需要更新的部分\n" +
                        "6.登录之后返回的token，需要将token放在右上角Authorize中，之后的请求都会携带token发送\n" +
                        "7.正确的使用姿势：打开两个swagger ui界面，一个用教师账号登录，一个用学生账号登录")
                // 文档版本
                .version("1.0.0")
                .build();
    }

}
